import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Input,
  Spin,
  Pagination,
  Table,
  Drawer,
  Form,
  Select,
  Button,
  Switch,
  message,
} from 'antd';
import styles from './index.less';
import editImg from '@/assets/basic/customDictionary/xiazi.png';
import sy from '@/assets/basic/customDictionary/sy.png';
import bianji from '@/assets/basic/customDictionary/bianji.png';
import edit from '@/assets/basic/customDictionary/edit.png';
import moreImg from '@/assets/knowledge/more.png';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';
import append from '@/assets/account/roleManagement/append.png';
import query from '@/assets/account/authorization/query.png';
import relevance from '@/assets/account/roleManagement/relevance.png';
import RoleCheck from './role';
import AddRoles from './add';

const Search = Input.Search;
const FormItem = Form.Item;
const { Option } = Select;

class UserManagement extends Component {
  state = {
    list: [
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
    ],
    login: false,
    total: '12',
    current: 1,
    pageSize: 10,
    addModel: false,
    addModelRedact: null,
    startSetLIst: ['在线', '离线'],
    startSetone: '', // 状态
    startSettwo: '', // 创建人
    Redactobj: '', // 编辑角色传参对象值
    namelist: [],
    query: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.newsysgetRolesByCreateUser();
  }

  unique5 = arr => {
    let x = new Set(arr);
    return [...x];
  };

  // 获取用户列表
  newsysgetRolesByCreateUser = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    console.log(currentUser);
    const userVo = {
      createUserId: currentUser.uid,
    };
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'userManagement/newsysgetRolesByCreateUser',
        payload: userVo,
        callback: res => {
          let startSetLIst = [];
          res.data.map(item => {
            startSetLIst.push(item.roleName);
          });
          console.log(startSetLIst);
          this.setState({ startSetLIst:['全部角色',this.unique5(startSetLIst)]});
          this.getRolesByCreateUserone();
        },
      });
    });
  };

  // 第一次调用
  getRolesByCreateUserone = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { current, pageSize, startSetone, query } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'userManagement/getRolesByCreateUser',
        payload: {
          createUserId: currentUser.uid,
        },
        callback: res => {
          console.log('列表数据', res);
          this.setState({
            list: res.data.list,
            total: res.data.total,
            login: false,
          });
        },
      });
    });
  };

  // 获取列表数据
  getRolesByCreateUser = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { current, pageSize, startSetone, query } = this.state;
    let obj = {}
    if(startSetone===''){
      obj = { createUserId: currentUser.uid,userId: query,page: String(current),rows: String(pageSize)}
    }
    if(query===''){
      obj = { createUserId: currentUser.uid,page: String(current),rows: String(pageSize), roleName: startSetone,}
    }
    if(query===''&&startSetone===''){
      obj = { createUserId: currentUser.uid,page: String(current),rows: String(pageSize)}
    }
    if(query&&startSetone){
      obj = { userId: query,createUserId: currentUser.uid,page: String(current),rows: String(pageSize),roleName: startSetone}
    }

    setTimeout(()=>{
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'userManagement/sysGetUserList',
          payload:obj,
          callback: res => {
            console.log('列表数据', res);
            this.setState({
              list: res.data.list,
              total: res.data.total,
              login: false,
            });
          },
        });
      });
    },100)

  };

  // // 修改用户列表
  // sysGetUserList = () => {
  //   this.setState({ login: true });
  //   const { dispatch, currentUser } = this.props;
  //   const { current, pageSize, startSetone, query } = this.state;
  //   this.reqRef = requestAnimationFrame(() => {
  //     dispatch({
  //       type: 'userManagement/sysGetUserList',
  //       payload: {
  //         createUseId: currentUser.uid,
  //         userId: query,
  //         page: current,
  //         rows: pageSize,
  //         roleName: startSetone,
  //       },
  //       callback: res => {
  //         console.log('列表数据', res);
  //         this.setState({
  //           list: res.data.list,
  //           total: res.data.total,
  //           login: false,
  //         });
  //       },
  //     });
  //   });
  // };

  onChangeTable = a => {
    console.log(a);
    this.setState({ current: a }, () => {
      this.getRolesByCreateUser();
    });
  };

  onShowSizeChangeTable = (a, b) => {
    console.log(a, b);
    this.setState({ pageSize: b, current: a }, () => {
      this.getRolesByCreateUser();
    });
  };

  onClosebj = () => {
    this.setState({
      addModel: false,
    });
  };

  append = () => {
    this.setState({
      addModel: true,
      addModelRedact: '1',
    });
  };

  Redact = item => {
    console.log(item);
    this.setState({
      addModel: true,
      addModelRedact: '2',
      Redactobj: item,
    });
  };

  deleteList = item => {
    // sysDelUser
    this.setState({ login: true });
    console.log(item);
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'userManagement/sysDelUser',
        payload: { uid: item.uid },
        callback: res => {
          console.log('列表数据', res);
          if (!res.code) {
            message.success(`${res.msg}`);
            this.setState(
              {
                login: false,
              },
              () => {
                this.getRolesByCreateUser();
              }
            );
          }
        },
      });
    });
  };

  operation = () => {
    // console.log
  };

  // 下拉框
  handleChangeSelect = value => {
    console.log(`selected ${value}`);
    if(value==='全部角色'){
      console.log('全部角色搜索')
      this.setState({ startSetone:'', current: 1 }, () => {
        this.getRolesByCreateUserone();
      });
    }else{
      this.setState({ startSetone: value, current: 1 }, () => {
        this.getRolesByCreateUser();
      });
    }

  };

  ceshi = index => {
    const { current, pageSize } = this.state;
    let a = (current - 1) * pageSize + index + 1;
    return a;
  };

  // 查询表单数据
  ABC = () => {
    const { startSetone, startSettwo } = this.state;
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        // type: 'knowledgeBaseSharing/fetchc',
        // payload: { robotId: currentUser.robotId },
        // callback: res => {
        //   console.log('列表数据', res);
        //   let temp = res;
        //   temp.map((item, index) => (item['key'] = index));
        //   this.setState({ treeList: temp });
        // },
      });
    });
  };

  rktbonChange = (item, index) => {
    console.log(item, index);
    const { list } = this.state;
    list[index].active = !item.active;
    this.setState({ list, login: true }, () => {
      console.log(this.state.list);
    });
    const { dispatch, currentUser } = this.props;
    const userVo = {
      nick: item.nick,
      // roles: user.uidname,
      uid: item.uid,
      // remakers: user.namems,
      active: !!item.active,
      // createUserId: currentUser.uid,
    };
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'userManagement/sysUpdateUser',
        payload: userVo,
        callback: res => {
          console.log('提交', res);
          if (!res.code) {
            message.success(`${res.msg}`);
            this.getRolesByCreateUser();
          }
        },
      });
    });
  };

  feel = item => {
    console.log(item);
    if (item === 'false') {
      this.setState(
        {
          addModel: false,
        },
        () => {
          this.getRolesByCreateUser();
        }
      );
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { addModelRedact, Redactobj } = this.state;
    const operationDate = [
      {
        title: '序号',
        // align: 'center',
        width: '100px',
        render: (item, todo, index) => {
          return <span>{this.ceshi(index)}</span>;
        },
      },
      {
        title: '姓名',
        dataIndex: 'nick',
        align: 'center',
        width: '200px',
      },
      {
        title: '账号',
        dataIndex: 'uid',
        align: 'center',
        width: '200px',
      },
      {
        title: '在线状态',
        // dataIndex: 'disabled ',
        align: 'center',
        width: '200px',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{item.disabled ? '在线' : '离线'}</span>
            </div>
          );
        },
      },
      {
        title: '角色名称',
        dataIndex: 'roleNames',
        align: 'center',
        width: '200px',
      },
      {
        title: '状态',
        width: '100px',
        align: 'center',
        render: (text, item, index) => {
          return (
            <div className="zdyswer">
              <Switch
                onClick={() => {
                  this.rktbonChange(item, index);
                }}
                defaultChecked
                checked={!item.active}
              />
            </div>
          );
        },
      },
      {
        title: '上次修改时间',
        dataIndex: 'updateTime',
        align: 'center',
        width: 'calc(25vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{moment(Number(item)).format('YYYY-MM-DD h:mm:ss')}</span>
            </div>
          );
        },
      },
      {
        title: '备注',
        dataIndex: 'remakers',
        align: 'center',
        width: '100px',
        // render(item) {
        //   return (
        //     <div className={styles.hull}>
        //       <span></span>
        //     </div>
        //   );
        // },
      },
      {
        title: '',
        width: '250px',
        align: 'center',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div className={styles.tool}>
                <img
                  onClick={() => {
                    this.Redact(item);
                  }}
                  src={bianji}
                />
                <img
                  onClick={() => {
                    this.deleteList(item);
                  }}
                  style={{ marginLeft: 15 }}
                  src={edit}
                />
              </div>
              <img src={moreImg} className={styles.more} />
            </div>
          );
        },
      },
    ];
    return (
      <div>
        <div className={styles.backgroundp}>
          <p style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
            用户管理
          </p>
          <div className={styles.imgbj}>
            <div className="zdyinputa">
              <Select
                size="large"
                placeholder="角色名称"
                style={{ width: 200, marginRight: 20 }}
                onChange={this.handleChangeSelect}
              >
                {this.state.startSetLIst.length
                  ? this.state.startSetLIst.map((item, index) => {
                      return <Option value={item}>{item}</Option>;
                    })
                  : null}
              </Select>
              <Search
                placeholder="请输入账号"
                onSearch={value => {
                  this.setState({ current: 1, query: value }, () => {
                    console.log(value);
                    this.getRolesByCreateUser();
                  });
                }}
                style={{ height: 40, width: 312 }}
              />
            </div>
            <div>
              <img style={{ cursor: 'pointer' }} onClick={this.append} src={append} />
            </div>
          </div>
          <div style={{ height: 20 }} />
          <Spin spinning={this.state.login}>
            <div className={styles.dabj} style={{ padding: '0px 20px' }}>
              <div className={styles.border} style={{ position: 'relative', right: '2px' }}>
                <Table
                  className="zdyTable"
                  columns={operationDate}
                  dataSource={this.state.list} //数据
                  pagination={false}
                />
              </div>
            </div>
            <Pagination
              style={{ textAlign: 'center', marginTop: 20 }}
              total={this.state.total}
              pageSize={this.state.pageSize} // 显示几条一页
              current={this.state.current} // 当前页
              showSizeChanger={true} // 是否显示可以设置几条一页的选项
              onChange={this.onChangeTable}
              onShowSizeChange={this.onShowSizeChangeTable}
              showTotal={() => `共 ${this.state.total} 条`}
            />
          </Spin>
        </div>
        <Drawer
          className="zdyset"
          title={
            <span>
              <Icon
                style={{ cursor: 'pointer' }}
                onClick={this.onClosebj}
                style={{ marginRight: 20 }}
                type="arrow-left"
              />
              {addModelRedact === '1' ? '新增' : '编辑'}
            </span>
          }
          placement="right"
          closable={false}
          onClose={this.onClosebj}
          visible={this.state.addModel}
          width="calc(100vw - 245px)"
          destroyOnClose
        >
          {addModelRedact === '1' ? (
            <AddRoles feel={this.feel} />
          ) : (
            <RoleCheck feel={this.feel} Redactobj={Redactobj} />
          )}
        </Drawer>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(UserManagement));
